#include "flash_movie.h"
#include "flash_driver.h"

#include "input/mouse.h"

#include "ui/ui_manager.h"
#include "graphics/graphics.h"

#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    

#include <cassert>

using namespace flash;
using namespace gameswf;

FlashMovie::FlashMovie() : 
	m_Pause(false),
	// seperate class later
	m_MovieVersion(1),
	m_MovieFPS(30),
	m_SpeedScale(1.0f),

	m_pClipEndFunc(0),
	m_pPayload(0),

	m_Looping(true)
{

}

FlashMovie::~FlashMovie()
{
}

bool	FlashMovie::Load(const std::string& File)
{
	m_pMovie = ui::UIManager::Instance().GetFlash()->Load(File);
	if (!m_pMovie)
	{
		_LOG(MSG_ERROR, "Can't create a movie Instance from flash file " << File);
		return false;
	}
	
	// is there some way to force a full pre-cache?

	//gameswf::set_current_root(m_pMovie);

	m_File = File;
	return true;
}

void	FlashMovie::Tick(float dt)
{
	if (!m_pMovie) return;
	if (!m_Pause)
	{
		input::Mouse*	pMouse = &GET_MOUSE();
		int MouseX = int(GraphicsUtil::WIDTH * pMouse->GetPos().x);
		int	MouseY = int(GraphicsUtil::HEIGHT * pMouse->GetPos().y);

		int	MouseButtons = 
			(int(pMouse->GetButtonState(input::Mouse::BUTTON_LEFT)->ButtonDown)) ||
			(int(pMouse->GetButtonState(input::Mouse::BUTTON_RIGHT)->ButtonDown) << 1);

		m_pMovie->notify_mouse_state(MouseX, MouseY, MouseButtons);

		// need a better way to handle mouse...
		m_pMovie->advance(dt * m_SpeedScale);

		// end of movie: m_pMovie->get_current_frame() + 1 == m_pMovieDef->get_frame_count()
		if (m_pMovie->get_current_frame() + 1 == m_pMovie->get_frame_count())
		{
			// end of clip
//			m_pMovie->
			if (m_Looping)		
			{
				m_pMovie->goto_frame(0);
			}

			if (m_pClipEndFunc) 
				m_pClipEndFunc(this, m_pPayload);
		}
	}
}


void	FlashMovie::Reset()
{
	if (m_pMovie) 
	{
		m_pMovie->goto_frame(0);
	}
}

void	FlashMovie::Render(const math::Vec2&	From, const math::Vec2& Size)
{
	int	w = GetGraphics()->GetScreenWidth();
	int	h = GetGraphics()->GetScreenHeight();

	if (From.x + Size.x > 1 || From.y+ Size.y  > 1 || From.x < 0 || From.y < 0) return;	// not visible
	if (m_pMovie)
	{
		m_pMovie->set_display_viewport(
			int(From.x * w) + Graphics::s_PixelOffsetX, 
			int(From.y * h) + Graphics::s_PixelOffsetY, 
			int(Size.x * w),int( Size.y * h));
		m_pMovie->set_background_alpha(0.0f);
		m_pMovie->display();
	}
	GetGraphics()->Start2D();
}

